#include<iostream>
#include "currency.h"

/**
 * Currency类的实现
 */
 // 构造函数
Currency::Currency(signType theSign, unsigned long theDollars, unsigned int theCents)
{
    setValue(theSign, theDollars, theCents);
}
// 设置值
void Currency::setValue(signType theSign, unsigned long theDollars, unsigned int theCents)
{
    if (theCents > 99)
        throw illegalParameterValue("Cents should be < 100");
    sign = theSign;
    dollars = theDollars;
    cents = theCents;
}
// 设置值
void Currency::setValue(double theAmount)
{
    if (theAmount < 0) {
        sign = minus;
        theAmount = -theAmount;
    }
    else
        sign = plus;
    dollars = (unsigned long)theAmount; // 截断整数部分
    cents = (unsigned int)((theAmount + 0.001 - dollars) * 100); // 四舍五入，提取两位小数
}
// 加法
Currency Currency::add(const Currency& x) const
{   // 两个货币相加
    long a1, a2, a3;
    Currency result;
    // this
    a1 = dollars * 100 + cents;
    if (sign == minus) a1 = -a1;
    // x
    a2 = x.dollars * 100 + x.cents;
    if (x.sign == minus) a2 = -a2;
    // result
    a3 = a1 + a2;
    if (a3 < 0) { result.sign = minus; a3 = -a3; }
    else result.sign = plus;
    result.dollars = a3 / 100;
    result.cents = a3 - result.dollars * 100;
    return result;
}
// 自身增长
Currency& Currency::increment(const Currency& x)
{
    *this = add(x);
    return *this;
}
// 输出
void Currency::output() const
{
    using std::cout;
    if (sign == minus) cout << "-";
    cout << '$' << dollars << '.';
    if (cents < 10)cout << '0';
    cout << cents;
}


/**
 * Currency2类的实现
 */

Currency2::Currency2(signType theSign, unsigned long theDollars, unsigned int theCents)
{
    setValue(theSign, theDollars, theCents);
}

void Currency2::setValue(signType theSign, unsigned long theDollars, unsigned int theCents)
{
    if (theCents > 99)
        throw illegalParameterValue("Cents should be < 100");
    amount = theDollars * 100 + theCents;
    if (theSign == minus) amount = -amount;
}

Currency2::Currency2(double theAmount)
{
    if (theAmount < 0) amount = (long)((theAmount - 0.001) * 100);
    else amount = (long)((theAmount + 0.001) * 100);
}

Currency2 Currency2::add(const Currency2& x) const
{
    Currency2 result;
    result.amount = amount + x.amount;
    return result;
}

void Currency2::output() const
{
    using std::cout;
    if (amount < 0) cout << '-';
    cout << '$' << getDollars() << '.';
    if (getCents() < 10) cout << '0';
    cout << getCents();
}
